# -*- coding:utf-8 -*-

import sys, os
from time import sleep
import unittest
from pywinauto.application import Application
from extendScript.RWExcleIMPL import ExcelImpl
from extendScript.ChangeTestCase import TestCaseNumIMPL
from extendScript.HTMLTestRunner import *


class setValueToGUI:
    def __init__(self, listValue=None):
        self.ei = ExcelImpl()
        self.listValue = self.ei.getOneTestCaseByExcel(testNo=listValue)
        self.startTilebuilder(self.listValue)

    def startTilebuilder(self, data):
        filePath = self.ei.getFilePath(type='TileBuilder')
        app = Application()

        try:
            self.app = app = app.connect(title_re="DEUTileBuilder")
            self.wfMain = wfMain = app.DEUTileBuilder
        except Exception as e:
            self.app = app = app.start(cmd_line=filePath)
            print e

            self.wfMain = wfMain = app.DEUTileBuilder
            wfMain.Wait('ready')

            # 暂停1s
            sleep(2)
            if data[1] == "影像数据":
                wfMain['影像'].Click()
            if data[1] == '高程数据':
                wfMain['高程'].Click()

            # 01、加载数据
            wfMain['添加'].Click()
            sleep(1)
            self.loadTestData(app, data[2], data[8])
            sleep(2)

            # 02、设置输出路径
            wfMain['浏览'].Click()
            sleep(1)
            outputdata = os.getcwd() + "\\outputdata\\DataSet\\" + data[0] + "_" + data[2] + "_" + str(int(data[3]))
            self.setOUTPutData(app['另存为'], outputdata)
            sleep(2)

            # 03、是否自动设置层行列号
            if data[4] == '否':
                self.setMinLevel(wfMain, int(data[5]))
                self.setMaxLevel(wfMain, int(data[6]))
            sleep(2)

            # 04、设置规格
            self.setSize(wfMain, int(data[3]))

            # 05、设置数据集编号
            self.setDataSetNO(wfMain, int(data[7]))
            sleep(2)

            # 06、开始切片
            # wfMain['开始'].Click()
            # while wfMain['Edit0'].IsEnabled() is False:
            #     sleep(2)
            #
            # sleep(1)

            # wfMain['关闭'].Click()
            #
            # app['WindowsForms10.Window.8.app.0.2bf8098_r11_ad1']['确定'].Click()

    def loadTestData(self, winfrom, dataformat, testData):
        testData = '"' + testData.replace(',', '" "') + '"'
        if dataformat == 'TIF' or dataformat == 'BIL':
            winfrom['打开']['ComboBox2'].Select(0)
        if dataformat == 'IMG' or dataformat == 'DEM':
            winfrom['打开']['ComboBox2'].Select(1)
        if dataformat == 'JPG':
            winfrom['打开']['ComboBox2'].Select(2)
        if dataformat == 'BMP':
            winfrom['打开']['ComboBox2'].Select(2)
        # winfrom[u'Edit1'].ClickInput()    #点击文本编辑框
        # winfrom[u'Edit1'].TypeKeys(testData)      #输入文本内容
        winfrom['打开']['Edit1'].SetEditText(testData)    #清空文本框内容再输入
        try:
            winfrom['打开'][u'打开(&O)'].Click()
            # sleep(1)
        except Exception as e1:
            print(e1)
            winfrom['打开'][u'打开(&O)'].Click()
        finally:
            try:
                winfrom['打开'][u'打开(&O)'].Click()
            except Exception as e3:
                print(e3)

        '''
        try:
            #winfrom.print_control_identifiers()
            winfrom['Button1'].Click()
            print("第一次打开.")
        except Exception as e:
            winfrom['打开(O)'].Click()
            print("第二次打开.")
            print(e+"错误出现了,检查目录或文件！")
        '''

    def setOUTPutData(self, winfrom, outputdata):
        # winfrom.print_control_identifiers()
        # winfrom['ComboBox0'].TypeKeys(outputdata)
        winfrom['Edit1'].SetEditText(outputdata)
        # sleep(1)
        # winfrom.Click()
        # winfrom[u"保存(S)"].Click()
        # winfrom[u"保存(S)"].Click()
        try:
            winfrom['Button1'].Click()
            print("第一次保存.")
        except Exception as e1:
            print(e1)
            winfrom[u'保存(S)'].Click()
            print("第二次保存.")
        finally:
            try:
                winfrom['Button1'].Click()
            except Exception as e1:
                print(e1)

    def setSize(self, wimfrom, size):
        if size == 128 or size == 8:
            wimfrom['ComboBox1'].Select(0)
        if size == 256 or size == 16:
            wimfrom['ComboBox1'].Select(1)
        if size == 512 or size == 32:
            wimfrom['ComboBox1'].Select(2)
        if size == 64:
            wimfrom['ComboBox1'].Select(3)

    def setMaxLevel(self, winfrom, strMaxLevel):
        if strMaxLevel > int(winfrom['ComboBox2'].ItemTexts()[len(winfrom['ComboBox2'].ItemTexts()) - 1]):
            winfrom['ComboBox2'].Select(len(winfrom['ComboBox2'].ItemTexts()) - 1)
        else:
            for index, value in enumerate(winfrom['ComboBox2'].ItemTexts()):
                if strMaxLevel == int(value):
                    winfrom['ComboBox2'].Select(index)
                    break

    def setMinLevel(self, winfrom, strMinLevel):
        sleep(2)
        if strMinLevel < int(winfrom['ComboBox3'].ItemTexts()[0]):
            winfrom['ComboBox3'].Select(0)
        else:
            for index, value in enumerate(winfrom['ComboBox3'].ItemTexts()):
                if strMinLevel == int(value):
                    winfrom['ComboBox3'].Select(index)
                    break

    def setDataSetNO(self, winfrom, strDataSetNO):
        winfrom['Edit0'].SetEditText(strDataSetNO)

    def getWinForm(self):
        return (self.app, self.wfMain, self.listValue)


class startTestGui(unittest.TestCase):
    def setUp(self):
        # self.verificationErrors = []
        self.tcn = TestCaseNumIMPL()

        self.svi = setValueToGUI(listValue=self.tcn.getValue())
        self.app, self.wfMain, self.listValue = self.svi.getWinForm()

    def testloadData(self):
        loadpath = self.listValue[8]
        self.assertEqual(loadpath.lower(), str(self.wfMain['LISTBOX2'].texts()[1]).lower())

    def testsetOUTPutData(self):
        filepath = os.getcwd() + "\\outputdata\\DataSet\\" + self.listValue[0] + "_" + self.listValue[2] + "_" + str(
            int(self.listValue[3]))
        self.assertEqual(filepath.lower(), str(self.wfMain["EDIT4"].texts()[0]).lower())

    def testsetSize(self):
        size = self.listValue[3]
        self.assertEqual(int(size), int(self.wfMain['COMBOBOX1'].selected_text()))

    def testsetMaxLevel(self):
        MaxLevel = self.listValue[6]
        self.assertEqual(int(MaxLevel), int(self.wfMain['COMBOBOX2'].selected_text()))

    def testsetMinLevel(self):
        MinLevel = self.listValue[5]
        self.assertEqual(int(MinLevel), int(self.wfMain['COMBOBOX3'].selected_text()))

    def testDataSetNO(self):
        DataSetNO = self.listValue[7]
        self.assertEqual(int(DataSetNO), int(self.wfMain['Edit1'].texts()[1]))

    def testSCFile(self):
        filepath = os.getcwd() + "\\outputdata\\DataSet\\" + self.listValue[0] + "_" + self.listValue[2] + "_" + str(
            int(self.listValue[3]))
        self.wfMain['开始'].Click()
        while self.wfMain['Edit0'].IsEnabled() is False:
            sleep(2)
        sleep(1)

        if self.listValue[1] == "影像数据":
            self.assertTrue(
                os.path.exists(filepath + '.DeuDom') and os.path.exists(filepath + '.idx') and os.path.exists(
                    filepath + '_0.db'))
        if self.listValue[1] == '高程数据':
            self.assertTrue(
                os.path.exists(filepath + '.DeuDem') and os.path.exists(filepath + '.idx') and os.path.exists(
                    filepath + '_0.db'))

    def tearDown(self):
        pass
        # self.tcn.addOneToFile()
        # self.wfMain['关闭'].Click()
        # self.app['WindowsForms10.Window.8.app.0.2bf8098_r11_ad1']['确定'].Click()


class initThisTester:
    def __init__(self):
        pass

    def delReportAndOutdata(self):
        print u"测试环境初始化，请稍后！"
        self.delReport()
        self.delOutdata()

    def delReport(self):
        self.delAllfolder(os.getcwd() + "\\ReportFile")

    def delOutdata(self):
        self.delAllfolder(os.getcwd() + "\\outputdata\\DataSet")

    def delAllfolder(self, filepath):
        for dfile in os.listdir(filepath):
            os.remove(filepath + "\\" + dfile)

    def closd_forme(self):
        try:
            app = Application().connect(title_re="DEUTileBuilder")
            wfMain = app.DEUTileBuilder

            sleep(1)

            wfMain['关闭'].Click()
            app['WindowsForms10.Window.8.app.0.2bf8098_r11_ad1']['确定'].Click()
        except Exception as e:
            print e

    def jltext_tilebuilder(self):
        ei = ExcelImpl()
        tcn = TestCaseNumIMPL()
        tcn.setValue("TC1")
        inittter = initThisTester()
        inittter.delReportAndOutdata()

        noTestcase = ei.getTestCaseByExcel(type='TileBuilder')

        for i in noTestcase:
            print "=" * 100
            print u"执行测试用例：" + i[0]
            print i

            tcn.setValue(i[0])
            suite = unittest.makeSuite(startTestGui)
            filename = os.getcwd() + "\\ReportFile\\" + i[0] + "_" + i[2] + "_" + str(int(i[3])) + "_Report.html"
            fp = file(filename, 'wb')
            runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u'自动化测试报告',
                                                   description=u'自动化测试报告,测试用例' + i[0] + "_" + i[2] + "_" + str(
                                                       int(i[3])))
            runner.run(suite)
            inittter.closd_forme()

        tcn.setValue("TC1")


if __name__ == '__main__':
    ei = ExcelImpl()
    tcn = TestCaseNumIMPL()
    tcn.setValue("TC1")
    inittter = initThisTester()
    inittter.delReportAndOutdata()

    noTestcase = ei.getTestCaseByExcel(type='TileBuilder')

    for i in noTestcase:
        print "=" * 100
        print u"执行测试用例：" + i[0]
        print i



        tcn.setValue(i[0])
        suite = unittest.makeSuite(startTestGui)
        filename = os.getcwd() + "\\ReportFile\\" + i[0] + "_" + i[2] + "_" + str(int(i[3])) + "_Report.html"
        fp = file(filename, 'wb')
        runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u'自动化测试报告',
                                               description=u'自动化测试报告,测试用例' + i[0] + "_" + i[2] + "_" + str(int(i[3])))
        runner.run(suite)
        inittter.closd_forme()

    tcn.setValue("TC1")
